﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace StockWatcher.Model
{
    public class StockStatistic
    {
        public StockStatistic()
        {
            Last30MinData = new List<MinStockPriceInfo>();
        }
        /// <summary>
        /// 股票代码
        /// </summary>
        public string RealCode { get; protected set; }
        /// <summary>
        /// 股票价格
        /// </summary>
        public double LastPrice { get; protected set; }
        /// <summary>
        /// 股票价格
        /// </summary>
        public double HighestPrice { get; protected set; }
        /// <summary>
        /// 股票价格
        /// </summary>
        public double LowestPrice { get; protected set; }
        /// <summary>
        /// 上次成交量，
        /// </summary>
        public long LastAmount { get; protected set; }


        public DateTime Time { get; protected set; }

        /// <summary>
        /// 获取最后N分钟之前的最新数据
        /// </summary>
        /// <param name="minute">分钟数</param>
        /// <returns></returns>
        public MinStockPriceInfo LastNMinPrice(int minute)
        {
            if (Last30MinData.Count < 1)
                return null;
            DateTime now = DateTime.Now;
            for (int i = Last30MinData.Count - 1; i >= 0; i--)
            {
                if ((now - Last30MinData[i].time).TotalMinutes > minute)
                    return Last30MinData[i];
            }
            return null;
        }

        /// <summary>
        /// 最后30分钟的数据,但是会保留最后一个30分钟之前的.
        /// </summary>
        public List<MinStockPriceInfo> Last30MinData { get; set; }

        public void Update(StockPriceInfo stockPrice)
        {
            RealCode = stockPrice.股票代码;
            Time = stockPrice.时间;
            LastPrice = stockPrice.当前价格;
            LastAmount = stockPrice.成交的股票数;
            HighestPrice = stockPrice.今日最高价;
            if (LastPrice > HighestPrice)
                HighestPrice = LastPrice;
            LowestPrice = stockPrice.今日最低价;
            if (LastPrice < LowestPrice)
                HighestPrice = LastPrice;
            Last30MinData.Add(new MinStockPriceInfo() { price = stockPrice.当前价格, time = stockPrice.时间 });
            //保留30分钟之内的数据和30分钟之前数据当中的最后一个.(保留最后一个,是考虑到下午开盘,和上午相差1.5个小时.多保留一个下午依然可以继续统计.不用等下午开盘半个小时)
            DateTime now = DateTime.Now;
            int i = Last30MinData.Count - 1;
            for (; i >= 0; i--)
            {
                if ((now - Last30MinData[i].time).TotalMinutes > 30)
                    break;
            }
            if (i > 0)
                Last30MinData.RemoveRange(0, i);
        }
    }
    public class MinStockPriceInfo
    {
        public double price;
        public DateTime time;
    }
}
